package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

type transresult struct {
	Src, Dst string
}

type translationInfo struct {
	Trans_result []transresult
	From, To     string
}

// 获取翻译内容、
func zhToEn(en string) (zh string) {
	params := url.Values{}
	Url, _ := url.Parse(TRANSLATION_API)
	params.Set("q", en)

	//如果参数中有中文参数,这个方法会进行URLEncode
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	fmt.Println(urlPath) //等同于https://www.xxx.com?age=23&name=zhaofan
	resp, _ := http.Get(urlPath)
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return fmt.Sprintf("API调用失败, err:%v\n", err)
	}
	var ti translationInfo
	json.Unmarshal(body, &ti)
	if len(ti.Trans_result) < 1 {
		return ""
	}
	return ti.Trans_result[0].Dst
}
